package com.engc.common.controller;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.engc.common.dao.DBExecuteException;
import com.engc.common.service.BaseService;
import com.engc.common.utils.BaseUtils;

/**
 * 菜单权限控制维护类
 * 
 * @author Administrator
 * 
 */
@Controller
@RequestMapping("/sysDataAcl")
public class SysDataAcl {

	@Resource
	BaseService baseService;

	@RequestMapping("/view")
	public String view() {
		return "system/sysdataacl/sysdataacl";
	}

	/**
	 * 获取当前角色已授权权限
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getRolePermission")
	@ResponseBody
	public Map<String, Object> getRolePermission(String id) {
		List<Map<String, Object>> privilegeList = baseService.Query("select  * from sys_authority_org  where authority_id=?", id);
		if (privilegeList == null || privilegeList.size() == 0) {
			return BaseUtils.getSuccessMessage(null);
		}

		List<Map<String, Object>> diclist = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> privilege : privilegeList) {
			Map<String, Object> temp = new HashMap<String, Object>();
			if ("sys_menu".equals(privilege.get("privilegeaccess"))) {
				temp.put("MenuID", privilege.get("privilegeaccesskey"));
				temp.put("BtnID", 0);
			} else {
				temp.put("MenuID", 0);
				temp.put("BtnID", privilege.get("privilegeaccesskey"));
			}
			diclist.add(temp);
		}
		return BaseUtils.getSuccessMessage(diclist);
	}

	/**
	 * 获取当前用户已授予的所有权限
	 * 
	 * @param request
	 * @return
	 */
	@RequestMapping("/getUserPermission")
	@ResponseBody
	public Map<String, Object> getUserPermission(@RequestParam("usercode") String usercode) {
		List<Map<String, Object>> privilegeList = baseService.Query("select  * from sys_acl where privilegemaster='user' and privilegemasterkey=?", usercode);
		if (privilegeList == null || privilegeList.size() == 0) {
			return BaseUtils.getSuccessMessage(null);
		}
		List<Map<String, Object>> diclist = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> privilege : privilegeList) {
			Map<String, Object> temp = new HashMap<String, Object>();
			if ("sys_menu".equals(privilege.get("privilegeaccess"))) {
				temp.put("MenuID", privilege.get("privilegeaccesskey"));
				temp.put("BtnID", 0);
			} else {
				temp.put("MenuID", 0);
				temp.put("BtnID", privilege.get("privilegeaccesskey"));
			}
			temp.put("Permit", Integer.valueOf(privilege.get("privilegeoperation").toString()) == 1);
			temp.put("Forbid", Integer.valueOf(privilege.get("privilegeoperation").toString()) == 0);
			diclist.add(temp);
		}
		return BaseUtils.getSuccessMessage(diclist);
	}

	/**
	 * 保存当前授权角色
	 * 
	 * @param jsondata
	 * @param roleid
	 * @return
	 * @throws DBExecuteException
	 */
	@RequestMapping("saveRolePermission")
	@ResponseBody
	@Transactional
	public Map<String, Object> saveRolePermission(@RequestParam("DataJSON") String jsondata, @RequestParam("RoleID") String roleid) throws DBExecuteException {
		boolean istrue = true;
		List<Map> permissions = JSON.parseArray(jsondata, Map.class);
		try {
			// 清空当前角色授权
			baseService.Delete("sys_acl", "privilegemaster='role' and privilegemasterkey=?", roleid);
			for (Map item : permissions) {
				// 是否分配权限
				boolean Permit = Boolean.valueOf(item.get("Permit") == null ? "false" : item.get("Permit").toString());
				// 是否按钮
				boolean isButton = Integer.valueOf(item.get("BtnID") == null ? "0" : item.get("BtnID").toString()) != 0;

				int MenuID = Integer.valueOf(item.get("MenuID") == null ? "0" : item.get("MenuID").toString());
				int BtnID = Integer.valueOf(item.get("BtnID") == null ? "0" : item.get("BtnID").toString());
				if (Permit) {
					Map<String, Object> record = new HashMap<String, Object>();
					record.put("privilegemaster", "role");
					record.put("privilegemasterkey", roleid);
					record.put("privilegeaccess", isButton ? "sys_button" : "sys_menu");
					record.put("privilegeaccesskey", isButton ? BtnID : MenuID);
					record.put("privilegeoperation", 1);
					baseService.Insert("sys_acl", record);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
			istrue = false;
			throw new DBExecuteException(e);
		}
		return istrue ? BaseUtils.getSuccessMessage("授权成功") : BaseUtils.getErrorMessage("授权失败，系统发生异常");
	}

	@RequestMapping("saveUserPermission")
	@ResponseBody
	@Transactional
	public Map<String, Object> saveUserPermission(@RequestParam("DataJSON") String jsonData, @RequestParam("UserID") String userid) throws DBExecuteException {
		boolean istrue = true;
		List<Map> permissions = JSON.parseArray(jsonData, Map.class);
		try {
			// 清空当前用户自定义授权
			baseService.Delete("sys_acl", "privilegemaster='user' and privilegemasterkey=?", userid);
			for (Map item : permissions) {
				// 是否分配权限
				boolean Permit = Boolean.valueOf(item.get("Permit") == null ? "false" : item.get("Permit").toString());
				// 是否禁止权限
				boolean Forbid = Boolean.valueOf(item.get("Forbid") == null ? "false" : item.get("Forbid").toString());
				// 是否按钮
				boolean isButton = Integer.valueOf(item.get("BtnID") == null ? "0" : item.get("BtnID").toString()) != 0;

				int MenuID = Integer.valueOf(item.get("MenuID") == null ? "0" : item.get("MenuID").toString());
				int BtnID = Integer.valueOf(item.get("BtnID") == null ? "0" : item.get("BtnID").toString());
				if (Permit || Forbid) {
					Map<String, Object> record = new HashMap<String, Object>();
					record.put("privilegemaster", "user");
					record.put("privilegemasterkey", userid);
					record.put("privilegeaccess", isButton ? "sys_button" : "sys_menu");
					record.put("privilegeaccesskey", isButton ? BtnID : MenuID);
					record.put("privilegeoperation", Permit ? 1 : 0);
					baseService.Insert("sys_acl", record);
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			istrue = false;
			throw new DBExecuteException(e);
		}

		return istrue ? BaseUtils.getSuccessMessage("授权成功") : BaseUtils.getErrorMessage("授权失败，系统发生异常");
	}

	/**
	 * 获取所有的资源文件 菜单-按钮
	 * 
	 * @return
	 */
	@RequestMapping("/getAccess")
	@ResponseBody
	public Map<String, Object> getAccess(HttpServletRequest request) {
		
		String orgid = BaseUtils.getCurrentUser(request).getOrgid();
		List<Map<String,Object>> allOrg = baseService.Query("select  *  from stb_org  where status=1  and orgid like ? order by nodepath", new String[]{orgid+"%"} );
		
		
		
		
//		List<Map<String, Object>> data = new ArrayList<Map<String, Object>>();
//		// 第一级节点数据
//		List<Map<String, Object>> parentMenuRecord = new ArrayList<Map<String, Object>>();
//		for (Map<String, Object> temp : menuRecords) {
//			if ("0".equals(temp.get("menuparentno"))) {
//				parentMenuRecord.add(temp);
//			}
//		}
//		// 循环二级菜单
//		for (Map<String, Object> parentmenu : parentMenuRecord) {
//			Map<String, Object> menu = ConvertMenu(parentmenu);
//			List<Map<String, Object>> submenus = new ArrayList<Map<String, Object>>();
//			for (Map<String, Object> menurecord : menuRecords) {
//				if (parentmenu.get("menuno").equals(menurecord.get("menuparentno"))) {
//					Map<String, Object> submenu = ConvertMenu(menurecord);
//					submenu.put("children", ConvertMenuButtonssubmenu(menurecord, buttonRecords));
//					submenus.add(submenu);
//				}
//			}
//			menu.put("children", submenus);
//			data.add(menu);
//		}
		return BaseUtils.getSuccessMessage(null);
	}

	/**
	 * 在菜单数据中加入按钮
	 * 
	 * @param submenu
	 * @param buttonRecords
	 * @return
	 */
	private List<Map<String, Object>> ConvertMenuButtonssubmenu(Map<String, Object> submenu, List<Map<String, Object>> buttons) {
		List<Map<String, Object>> mybuttons = new ArrayList<Map<String, Object>>();
		for (Map<String, Object> button : buttons) {
			if (button.get("menuno").equals(submenu.get("menuno"))) {
				Map<String, Object> mybutton = new HashMap<String, Object>();
				mybutton.put("AccessName", button.get("btnname"));
				mybutton.put("AccessIcon", button.get("btnicon"));
				mybutton.put("AccessNo", button.get("btnno"));
				mybutton.put("MenuID", 0);
				mybutton.put("BtnID", button.get("btnid"));
				mybuttons.add(mybutton);
			}
		}
		return mybuttons;
	}

	/**
	 * 转换成Menu 所需要的格式
	 * 
	 * @param menu
	 * @return
	 */
	private Map<String, Object> ConvertMenu(Map<String, Object> obj) {
		Map<String, Object> cmenu = new HashMap<String, Object>();
		cmenu.put("AccessName", obj.get("menuname"));
		cmenu.put("AccessIcon", obj.get("menuicon"));
		cmenu.put("AccessNo", obj.get("menuno"));
		cmenu.put("MenuID", obj.get("menuid"));
		cmenu.put("BtnID", 0);
		return cmenu;
	}

	@RequestMapping("/insert")
	public Map<String, Object> insert(HttpServletRequest request) {

		return BaseUtils.getSuccessMessage("授权成功");
	}

	@RequestMapping("/update")
	public Map<String, Object> update(HttpServletRequest request) {

		return BaseUtils.getSuccessMessage("授权更改成功");
	}

	@Resource
	public void setBaseService(BaseService baseService) {
		this.baseService = baseService;
	}

}
